package com.bill99.golden.inf.sso.service;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bill99.golden.inf.sso.mdp.dto.DestroyTokenRequestDto;
import com.bill99.golden.inf.sso.mdp.dto.ValidateTokenRequestDto;
import com.bill99.golden.inf.sso.mdp.dto.ValidateTokenResponseDto;

public class ClientTokenService {
	private static Log log = LogFactory.getLog(ClientTokenService.class);
	private static final Map<String, ValidateTokenResponseDto> tokenBufMap = new ConcurrentHashMap<String, ValidateTokenResponseDto>();
	private static int timeoutMinutes = 10;

	public static void bufferTokenInfo(String token,
			ValidateTokenResponseDto tokenInfo) {
		if (tokenInfo != null) {
			tokenInfo.refreshUpdateTime();
			tokenBufMap.put(token, tokenInfo);
		}
		log.debug("缓存SSO信息bufferTokenInfo：" + tokenInfo);
	}

	/**
	 * 
	 * @param r
	 * @return 如果返回为null，则需要到CAS做进一步的认证
	 */
	public static ValidateTokenResponseDto validateTokenFromBuffer(
			ValidateTokenRequestDto r) {
		log.debug("验证SSO信息：validateTokenFromBuffer" + r);
		if (r == null || r.getToken() == null || r.getToken().trim().equals("")) {
			return null;
		}
		String checkCode = TokenService.generateCheckCode(r.getUserIp(),
				r.getExplorerType());
		ValidateTokenResponseDto response = tokenBufMap.get(r.getToken());
		if (response == null) {
			// 没有Token
			return null;
		}
		if (checkCode.equals(response.getCheckCode())) {
			long ut = response.getUpdateTime();
			int outTime = (int) (System.currentTimeMillis() - ut);
			if (outTime <= ClientTokenService.timeoutMinutes * 60000) {
				response.refreshUpdateTime();
				response.setValid(true);
				return response;
			} else {
				// 超时则销毁
				tokenBufMap.remove(r.getToken());
				return null;
			}
		} else {
			// 验证码不正确，则token很可能是伪造的
			ValidateTokenResponseDto res = new ValidateTokenResponseDto();
			res.setValid(false);
			return res;
		}
	}

	public static void destroyTokenFromBuffer(DestroyTokenRequestDto r) {
		if (r == null)
			return;
		if (r.getToken() == null || r.getToken().trim().equals("")) {
			return;
		}
		String checkCode = TokenService.generateCheckCode(r.getUserIp(),
				r.getExplorerType());
		log.debug("销毁SSO登录信息：destroyTokenFromBuffer" + r);
		if (r.getToken() == null) {
			return;
		}
		ValidateTokenResponseDto s = tokenBufMap.get(r.getToken());
		if (s != null) {
			if (checkCode.equals(s.getCheckCode())) {
				tokenBufMap.remove(r.getToken());
			}
		}
	}

	public static int getTotalBufferedSSOCount() {
		return tokenBufMap.size();
	}

	public static void checkSessionTimeOut() {
		log.info("start checkSessionTimeOut.........time="
				+ new java.util.Date());
		Iterator<Map.Entry<String, ValidateTokenResponseDto>> it = tokenBufMap
				.entrySet().iterator();
		int cnt = 0;
		while (it.hasNext()) {
			Map.Entry<String, ValidateTokenResponseDto> en = it.next();
			ValidateTokenResponseDto s = en.getValue();
			if (s == null)
				continue;
			long ut = s.getUpdateTime();
			int outTime = (int) (System.currentTimeMillis() - ut);
			String token = en.getKey();
			if (outTime > ClientTokenService.timeoutMinutes * 60000) {
				// session超时
				tokenBufMap.remove(token);
				cnt++;
			}
		}
		log.info("end checkSessionTimeOut.........timeoutSessions=" + cnt
				+ "  time=" + new java.util.Date());
	}
}
